﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CRM.Entity;
using CRM.BLL;
using System.Text;
using DP.Common;
using DP.Web.UI;
using System.Data;


namespace CRM.Web.OutboundManage
{
    public partial class VoiceAssignment : Common.PageBase
    {

        T_USER_BLL userBll = new T_USER_BLL();
        private T_DEPARTMENT_BLL departmentBll = new T_DEPARTMENT_BLL();
        private T_VOICEMAIL_BLL voiceMailBll = new T_VOICEMAIL_BLL();
        private T_PHONEAREA_BLL phoneAreaBll = new T_PHONEAREA_BLL();



        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageHelper.SetPrePageUrl(this.Page);
            if (PageHelper.GetQueryString(this.Page, "PageTarget") != "Opener")
            {
                PageHelper.SetGoBackUrl(this.Page, btnCancel, StaticConstant.NotBackUrl);
                btnCancel.Attributes["onclick"] = UserLoginInfo.FilterBackUrl(btnCancel.Attributes["onclick"]);
            }
            else
            {
                PageHelper.SetClose(this.Page, btnCancel);
                btnCancel.Value = "关 闭";
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlPROVINCEBinding();
                ddlCITYBinding();
                ddlDepartmentBinding();
                gvDataBindingUser();
                gvListVoiceDataBinding();
                pageInit();
            }
        }

        private void pageInit()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(String.Format(" and DNIS like '{0}%' ", UserLoginInfo.GetLoginInfo().BusinessdivisionEntity.VIRTUALGROUP));
            stringBuilder.Append(" and ALLOCATEDTIME is null ");
            stringBuilder.Append(String.Format(" and STATUS = '{0}' ", ((int)VoiceStatus.待回电).ToString()));

            //lblLostCount.Text = voiceMailBll.GetCount(stringBuilder.ToString()).ToString();
            //lblLostTelCount.Text = voiceMailBll.GetDistinctTable("ANI", stringBuilder.ToString()).Rows.Count.ToString();
            //txtAssignmentNumber.Text = "0";
        }


        private void ddlPROVINCEBinding()
        {
            DataTable dt = phoneAreaBll.GetDistinctTable("PROVINCE", " and PROVINCE is not null ");
            ddlPROVINCE.DataSource = dt;
            ddlPROVINCE.DataTextField = "PROVINCE";
            ddlPROVINCE.DataValueField = "PROVINCE";
            ddlPROVINCE.DataBind();
            ddlPROVINCE.Items.Insert(0, new ListItem("", ""));
        }

        private void ddlCITYBinding()
        {
            ddlCITY.Items.Clear();
            if (!String.IsNullOrEmpty(ddlPROVINCE.SelectedValue.Trim()))
            {
                DataTable dt = phoneAreaBll.GetDistinctTable("CITY", String.Format(" and CITY is not null and PROVINCE = '{0}' ", ddlPROVINCE.SelectedValue.Trim()));
                ddlCITY.DataSource = dt;
                ddlCITY.DataTextField = "CITY";
                ddlCITY.DataValueField = "CITY";
                ddlCITY.DataBind();
            }
            ddlCITY.Items.Insert(0, new ListItem("", ""));
        }

        private void ddlDepartmentBinding()
        {
            StringBuilder sql = new StringBuilder();
            if (!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");

            }
            sql.Append(String.Format(" and ISCENTER = '{0}' ", ((int)DepartmentType.呼叫中心).ToString()));
            sql.Append(" and DepartmentID in (select DepartmentID from T_User ) ");

            ddlDepartment.DataSource = departmentBll.GetList(sql.ToString());
            ddlDepartment.DataTextField = "DEPARTMENTNAME";
            ddlDepartment.DataValueField = "DEPARTMENTID";
            ddlDepartment.DataBind();
            if (!UserLoginInfo.IsAdministrator())
            {
                ddlDepartment.Enabled = false;
                ddlDepartment.SelectedValue = _userLoginInfo.UserEntity.DEPARTMENTID.ToString();
            }

        }



        /// <summary>
        /// Gvs the list lost data binding.
        /// </summary>
        private void gvListVoiceDataBinding()
        {

            #region 查询条件字符串
            StringBuilder sqlAreaNo = this.GetConditionsAreaNo();
            StringBuilder sqlSectionNo = this.GetConditionsSectionNo();
            #endregion


            List<T_VOICEMAIL_Entity> listAreaNo = new List<T_VOICEMAIL_Entity>();
            List<T_VOICEMAIL_Entity> listSectionNo = new List<T_VOICEMAIL_Entity>();

            //获取总的记录条数
            //gvListLost.RecordCount = (int)callLossBll.GetCount(sql.ToString());

            listAreaNo = voiceMailBll.GetList(sqlAreaNo.ToString(), gvListVoice.SortConditions);
            if (!String.IsNullOrEmpty(ddlPROVINCE.SelectedValue.Trim()))
            {
                listSectionNo = voiceMailBll.GetList(sqlSectionNo.ToString(), gvListVoice.SortConditions);
            }
            listAreaNo.AddRange(listSectionNo);
            listAreaNo = listAreaNo.Distinct<T_VOICEMAIL_Entity>(new Compare<T_VOICEMAIL_Entity>((x, y) => (null != x && null != y) && (x.ID == y.ID))).ToList();

            gvListVoice.DataSource = listAreaNo;
            gvListVoice.DataKeyNames = new string[] { "ID" };
            gvListVoice.DataBind();
            lblCount.Text = listAreaNo.Count.ToString();
        }

        /// <summary>
        /// Gets the conditions area no.
        /// </summary>
        /// <returns></returns>
        private StringBuilder GetConditionsAreaNo()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(String.Format(" and DNIS like '{0}%' ", UserLoginInfo.GetLoginInfo().BusinessdivisionEntity.VIRTUALGROUP));
            stringBuilder.Append(" and ALLOCATEDTIME is null ");
            stringBuilder.Append(String.Format(" and STATUS = '{0}' ", ((int)VoiceStatus.待回电).ToString()));
            if (!String.IsNullOrEmpty(ddlCITY.SelectedValue.Trim()))
            {
                stringBuilder.Append(String.Format(" and AREANO in (select AREANO from t_phonearea where PROVINCE = '{0}' and CITY = '{1}' ) ", ddlPROVINCE.SelectedValue.Trim(), ddlCITY.SelectedValue.Trim()));
            }
            else if (!String.IsNullOrEmpty(ddlPROVINCE.SelectedValue.Trim()))
            {
                stringBuilder.Append(String.Format(" and AREANO in (select AREANO from t_phonearea where PROVINCE = '{0}' ) ", ddlPROVINCE.SelectedValue.Trim()));
            }
            return stringBuilder;
        }

        /// <summary>
        /// Gets the conditions section no.
        /// </summary>
        /// <returns></returns>
        private StringBuilder GetConditionsSectionNo()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(String.Format(" and DNIS like '{0}%' ", UserLoginInfo.GetLoginInfo().BusinessdivisionEntity.VIRTUALGROUP));
            stringBuilder.Append(" and ALLOCATEDTIME is null ");
            stringBuilder.Append(String.Format(" and STATUS = '{0}' ", ((int)VoiceStatus.待回电).ToString()));
            if (!String.IsNullOrEmpty(ddlCITY.SelectedValue.Trim()))
            {
                stringBuilder.Append(String.Format(" and  SECTIONNO in (select SECTIONNO from t_phonearea where PROVINCE = '{0}' and CITY = '{1}')  ", ddlPROVINCE.SelectedValue.Trim(), ddlCITY.SelectedValue.Trim()));
            }
            else if (!String.IsNullOrEmpty(ddlPROVINCE.SelectedValue.Trim()))
            {
                stringBuilder.Append(String.Format(" and  SECTIONNO in (select SECTIONNO from t_phonearea where PROVINCE = '{0}')  ", ddlPROVINCE.SelectedValue.Trim()));
            }
            return stringBuilder;
        }


        /// <summary>
        /// 生成查询条件字符串
        /// </summary>
        private StringBuilder GenerationSQLStringUser()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(" and (ISSYSTEMADMIN <> '1' or ISSYSTEMADMIN is null) ");
            sql.Append(String.Format(" and DEPARTMENTID = '{0}' ", ddlDepartment.SelectedValue));
            if (!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");

            }
            return sql;

        }

        /// <summary>
        /// 页面数据绑定
        /// </summary>
        private void gvDataBindingUser()
        {
            #region 查询条件字符串
            StringBuilder sql = GenerationSQLStringUser();
            #endregion

            List<T_USER_Entity> list;

            //获取总的记录条数
            gvList.RecordCount = (int)userBll.GetCount(sql.ToString());

            list = userBll.GetList(sql.ToString(), gvList.SortConditions);

            gvList.DataSource = list;
            gvList.DataKeyNames = new string[] { "USERID", "UserName", "LoginName" };
            gvList.DataBind();

        }

        protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvDataBindingUser();
        }

        protected void btnAssign_Click(object sender, EventArgs e)
        {
            string Sets = "";
            string setsTemplate = " ASSIGNEDPERSONID = {0}, ASSIGNEDPERSONNAME = '{1}', DISTRIBUTIONPEOPLEID = {2}, DISTRIBUTIONPEOPLENAME = '{3}', ALLOCATEDTIME = sysdate, BUSINESSDIVISIONID = {4}, BUSINESSDIVISIONNAME = '{5}', BUSINESSDIVISIONCODE = '{6}', LIMITED = '{7}'      ";

            T_USER_Entity user;
            List<T_USER_Entity> userList = GetSelected(gvList);
            if (userList.Count == 0)
            {
                PageHelper.ShowMessage(this.Page, "请选择分配的目标人！");
                return;
            }


            List<String> voiceIdList = GetSelectedVoiceID(gvListVoice);
            if (voiceIdList.Count == 0)
            {
                PageHelper.ShowMessage(this.Page, "请选择分配的呼损电话！");
                return;
            }
            int voiceAssignmentLimited = StringHelper.ToInt(configBll.GetCacheValueByName(this.Page, "VoiceAssignmentLimited"), 0);
            int userCount = userList.Count;
            int voiceCount = voiceIdList.Count;


            //int assignCount = StringHelper.ToInt(txtAssignmentNumber.Text.Trim());
            //int voiceCount = StringHelper.ToInt(lblLostTelCount.Text.Trim());
            //if (assignCount == 0)
            //{
            //    assignCount = IntHelper.divideMax(voiceCount, userList.Count);
            //}

            //StringBuilder Conditions = new StringBuilder();
            //Conditions.Append(String.Format(" and DNIS like '{0}%' ", UserLoginInfo.GetLoginInfo().BusinessdivisionEntity.VIRTUALGROUP));
            //Conditions.Append(" and ALLOCATEDTIME is null ");
            //Conditions.Append(String.Format(" and STATUS = '{0}' ", ((int)VoiceStatus.待回电).ToString()));

            //DataTable dt = voiceMailBll.GetDistinctTable("ANI", Conditions.ToString());
            //int index = 0;
            StringBuilder temp = new StringBuilder();
            try
            {

                for (int i = 0; i < voiceCount; i++)
                {
                    user = userList[i % userCount];
                    Sets = String.Format(setsTemplate, user.USERID, user.USERNAME, _userLoginInfo.UserEntity.USERID, _userLoginInfo.UserEntity.USERNAME,
                       _userLoginInfo.UserEntity.BUSINESSDIVISIONID, _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME, _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE, voiceAssignmentLimited);
                    voiceMailBll.Update(Sets, String.Format(" and ID = '{0}' ", voiceIdList[i].ToString()), 1);
                }
                //foreach (var user in userList)
                //{
                //    //temp = new StringBuilder();
                //    //for (int i = 0; i < assignCount; i++)
                //    //{

                //    //    if (temp.Length > 0)
                //    //    {
                //    //        temp.Append(",");
                //    //    }
                //    //    temp.Append("'").Append(DataTableHelper.GetColumnValueToString(dt, index * assignCount + i, "ANI")).Append("'");
                //    //}
                //    //temp.Insert(0, " and ANI in ( ");
                //    //temp.Append(" ) ");
                    
                //    //Sets = String.Format(setsTemplate, user.USERID, user.USERNAME, _userLoginInfo.UserEntity.USERID, _userLoginInfo.UserEntity.USERNAME,
                //    //    _userLoginInfo.UserEntity.BUSINESSDIVISIONID, _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME, _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE,
                //    //    StringHelper.ToInt(configBll.GetCacheValueByName(this.Page, "VoiceAssignmentLimited"), 0));
                //    //voiceMailBll.Update(Sets, Conditions.ToString() + temp.ToString());
                //    //index++;
                //}
                gvListVoiceDataBinding();
                PageHelper.ShowMessage(this.Page, "分配成功！");
            }
            catch (Exception ex)
            {
                PageHelper.ShowMessage(this.Page, "分配失败！" + ex.Message);
            }


        }

        private List<T_USER_Entity> GetSelected(GridView gv)
        {
            List<T_USER_Entity> list = new List<T_USER_Entity>();
            if (gv == null) return list;
            T_USER_Entity entity;
            CheckBox cb;
            foreach (GridViewRow gvr in gv.Rows)
            {
                cb = gvr.FindControl("cbItem") as CheckBox;
                if (cb == null) continue;
                if (!cb.Checked) continue;
                entity = new T_USER_Entity();
                entity.USERID = StringHelper.ToInt(gv.DataKeys[gvr.RowIndex].Values["USERID"].ToString(), 0);
                entity.USERNAME = gv.DataKeys[gvr.RowIndex].Values["UserName"].ToString();
                entity.LOGINNAME = gv.DataKeys[gvr.RowIndex].Values["LoginName"].ToString();
                list.Add(entity);
            }
            return list;
        }

        private List<string> GetSelectedVoiceID(GridView gv)
        {
            List<string> list = new List<string>();
            if (gv == null) return list;
            CheckBox cb;
            foreach (GridViewRow gvr in gv.Rows)
            {
                cb = gvr.FindControl("cbItem") as CheckBox;
                if (cb == null) continue;
                if (!cb.Checked) continue;
                list.Add(gv.DataKeys[gvr.RowIndex].Values["ID"].ToString());
            }
            return list;
        }

        protected void ddlPROVINCE_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCITYBinding();
        }


        protected void btnSearch_Click(object sender, EventArgs e)
        {
            gvListVoiceDataBinding();
        }


    }
}
